<template>
  <div>

    <!-- 主要内容 -->
    <el-main>
      <el-header>
        <el-col :span="6">
          <span>项目编号：{{ formData.projectCode }}</span>
        </el-col>
        <el-col :span="6">
          <span>项目名称：{{ formData.projectName  }}</span>
        </el-col>
        <el-col :span="6">
          <span v-if="formData.purchaseCategoryId === 1">采购类别：货物类</span>
          <span v-else-if="formData.purchaseCategoryId === 2">采购类别：服务类</span>
          <span v-else-if="formData.purchaseCategoryId === 3">采购类别：工程类</span>
          <span v-else>采购类别：其他采购类别</span>
        </el-col>
        <el-col :span="6">
          <span>预算金额：{{ formData.budget }}元</span>
        </el-col>
      </el-header>

      <!-- 表格 -->
      <el-table :data="supplierData" style="width: 100%" border>
        <el-table-column v-if="false" prop="id" label="序号"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
        <el-table-column prop="contact" label="联系人"></el-table-column>
        <el-table-column prop="telephone" label="联系电话"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)"  :disabled="formData.potentialsupplierSubmitStatus === '已提交'">编辑</el-button>
            <el-button @click="delPS(scope.row)"  :disabled="formData.potentialsupplierSubmitStatus === '已提交'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination class="pagination-container"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[10, 20, 30, 50]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="totalItems"
      ></el-pagination>

      <div style="margin-top: 20px">
        <el-col :span="11">
          <span>提交审批状态：{{ formData.potentialsupplierSubmitStatus }}</span>
        </el-col>
        <el-col :span="11">
          <span>提交审批时间：{{ formData.potentialsupplierSubmitTime }}</span>
        </el-col>
        <el-col :span="11">
          <span >审批状态：{{ formData.potentialsupplierApproveStatus }}</span>
        </el-col>
        <el-col :span="11">
          <span>审批时间：{{ formData.potentialsupplierApproveTime }}</span>
        </el-col>
      </div>

      <!-- 添加按钮和返回按钮 -->
      <div style="margin-left: 100px;margin-top: 100px;">
                <span style="margin-top: 40px;margin-left: 20px">
          <el-button @click="addDialogVisible = true" type="primary" :disabled="formData.potentialsupplierSubmitStatus === '已提交'">添加潜在供应商</el-button>
        </span>
        <span style="margin-left: 40px;margin-top: 40px">
          <el-button  @click="submit" type="primary" :disabled="formData.potentialsupplierSubmitStatus === '已提交'">提交审批</el-button>
        </span>
        <span style="margin-top: 40px;margin-left: 40px;">
          <el-button @click="goBack" type="primary">返回</el-button>
        </span>

      </div>
    </el-main>


    <!-- 编辑对话框 -->
    <el-dialog title="编辑供应商" :visible.sync="editDialogVisible">
      <el-form ref="editForm" :model="editedSupplier" label-width="100px">
        <el-form-item label="供应商名称">
          <el-input v-model="editedSupplier.supplierName"></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="editedSupplier.contact"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editedSupplier.telephone"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="saveEdit">保 存</el-button>
      </div>
    </el-dialog>



    <!-- “添加”对话框 -->
    <el-dialog :visible.sync="addDialogVisible" title="添加供应商" @close="closeAddDialog">
      <el-form ref="addPotentialSuppliers" :rules="rules" :model="addPotentialSuppliers" label-width="100px" >
        <el-form-item label="供应商名称">
          <el-input v-model="addPotentialSuppliers.supplierName"></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="addPotentialSuppliers.contact"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="addPotentialSuppliers.telephone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAddDialog">取消</el-button>
        <el-button type="primary" @click="saveAdd">保存</el-button>
      </span>
    </el-dialog>



  </div>
</template>

<script>
import {SubmitPotentialSuppliers, updatePotentialSuppliers} from "@/api/potentialSuppliers/potentialSuppliers.js";
import { delPotentialSuppliers } from "@/api/potentialSuppliers/potentialSuppliers.js";
import { addPotentialSuppliers } from "@/api/potentialSuppliers/potentialSuppliers.js";
import { selectAllPotentialSuppliers } from "@/api/potentialSuppliers/potentialSuppliers.js";

export default {
  data() {
    return {
      //保存传递过来的数据
      formData: {
        projectCode: '',
        projectName: '',
        purchaseCategoryId: '',
        budget: '',
        potentialsupplierSubmitTime:'',
        potentialsupplierSubmitStatus:'',
        potentialsupplierSuggestion:'',
        potentialsupplierApproveStatus:'',
        potentialsupplierApproveP:'',
        potentialsupplierApproveTime:'',
        quaSubmit:'',
        projectId:'',
      },
      rules: {
        contact: [{required: true, message: '请输入', trigger: ['blur', 'change']}],
        telephone: [{required: true, message: '请输入', trigger: ['blur', 'change']}],
        supplierName: [{required: true, message: '请输入', trigger: ['blur', 'change']}],
      },
      //table表格里的新数据,此处添加的值仅为测试值，上线代码前请将其删除
      supplierData: [],

      //显示编辑对话框
      editDialogVisible: false,
      //点击修改时，数据保存在临时数组中
      editedSupplier: {
        id:'',
        supplierName: '',
        contact: '',
        telephone: '',
      },

      //分页
      currentPage: 1,
      pageSize: 10,
      totalItems: 0,

      //显示添加对话框
      addDialogVisible: false,
      //点击添加时，数据保存在临时数组中
      addPotentialSuppliers: {
        id: '',
        supplierName: '',
        contact: '',
        telephone: '',
        projectId: '',
      },
      deleteDialogVisible: false,
      showCancelMessage: true,
    };
  },

  created() {
    // 接收路由传递的数据
    this.formData.projectCode = this.$route.params.projectCode;
    this.formData.projectName = this.$route.params.projectName;
    this.formData.purchaseCategoryId = this.$route.params.purchaseCategoryId;
    this.formData.budget = this.$route.params.budget;
    this.formData.potentialsupplierSubmitTime = this.$route.params.potentialsupplierSubmitTime;
    this.formData.potentialsupplierSubmitStatus = this.$route.params.potentialsupplierSubmitStatus;
    this.formData.potentialsupplierSuggestion = this.$route.params.potentialsupplierSuggestion;
    this.formData.potentialsupplierApproveStatus = this.$route.params.potentialsupplierApproveStatus;
    this.formData.potentialsupplierApproveP = this.$route.params.potentialsupplierApproveP;
    this.formData.potentialsupplierApproveTime = this.$route.params.potentialsupplierApproveTime;
    this.formData.quaSubmitP = this.$route.params.quaSubmitP;
    this.formData.projectId = this.$route.params.projectId;

    //调用方法初始化数据
    this.selectAddPotentialSuppliers();
  },

  methods: {

    handleSizeChange(val) {
      this.pageSize = val
      this.selectAddPotentialSuppliers()
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.selectAddPotentialSuppliers()
    },


  //初始化supplierData里的数据
    async selectAddPotentialSuppliers() {
      let data = this.formData.projectId+'/'+this.currentPage + '/' + this.pageSize;
      console.log(this.formData.potentialsupplierSubmitStatus)
      try {
        const response = await selectAllPotentialSuppliers(data);
        this.supplierData = response.data.data.record;
        this.totalItems = this.supplierData.length;
      } catch (error) {
        console.error('Error fetching supplier data:', error);
      }
    },

    //当点击编辑按钮，出现对话框
    handleEdit(row) {
      // 克隆行数据以防止直接修改原始数据
      this.editedSupplier.id = row.id;
      this.editedSupplier.supplierName = row.supplierName;
      this.editedSupplier.contact = row.contact;
      this.editedSupplier.telephone = row.telephone;
      this.editedSupplier.projectI=row.projectId;
      this.editDialogVisible = true;
    },

    //当点击对话框的取消按钮，关闭对话框
    closeDialog() {
      this.editDialogVisible = false;
      this.$refs.editForm.resetFields();
    },

    //当点击对话框中的保存时，修改原有数据并关闭对话框
    async saveEdit() {
      // 在supplierData数组中查找已编辑行的索引
      // this.supplierData.splice(this.editingIndex, 1, this.editedSupplier);

      try {
        const regex = /^(13[0-9]{9})|(15[0-9]{9})|(17[0-9]{9})|(18[0-9]{9})|(19[0-9]{9})$/;
        if(regex.test(this.editedSupplier.telephone)){
          const response = await updatePotentialSuppliers(this.editedSupplier)
          // this.supplierData = response.data.data.record
          this.editedSupplier = {
            id: '',
            contact: '',
            telephone: '',
            supplierName: '',
            projectId: '',
          }
          // 重置字段信息
          this.$refs["editForm"].resetFields();
          // 重新获取
          await this.selectAddPotentialSuppliers()
          this.editDialogVisible = false
        }else{
          this.$message.error("手机号输入不正确，请重新输入")
        }


      } catch (error) {
        console.error('Error updating supplier data:', error);
      }
    },

    delPS(row) {
      this.$confirm('确认删除该项吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        let res = await delPotentialSuppliers(row.id)
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          await this.selectAddPotentialSuppliers()

        } else {
          this.$message.error(res.data.msg)
        }

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },


    //当点击取消按钮，取消表单
    closeAddDialog() {
      this.$refs["addPotentialSuppliers"].resetFields();
      this.addDialogVisible = false
      this.addPotentialSuppliers = {
        id: '',
        supplierName: '',
        contact: '',
        telephone: '',
      }
      if (this.showCancelMessage) {
        this.$message({
          message: '已取消操作',
        });
      }
    },

    async saveAdd() {
      this.$refs.addPotentialSuppliers.validate(async (valid) => {
        this.addPotentialSuppliers.projectId=this.$data.formData.projectId
        if (valid && (this.addPotentialSuppliers.supplierName !== '')) {
          const regex = /^(13[0-9]{9})|(15[0-9]{9})|(17[0-9]{9})|(18[0-9]{9})|(19[0-9]{9})$/;
          if(regex.test(this.addPotentialSuppliers.telephone)){
            let res = await addPotentialSuppliers(this.addPotentialSuppliers)
            if (res.data.code === 200) {
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.addPotentialSuppliers = {
                id: '',
                supplierName: '',
                contact: '',
                telephone: '',
                projectId: '',
              }
              // 重置字段信息
              this.$refs["addPotentialSuppliers"].resetFields();
              // 获得个人的
              await this.selectAddPotentialSuppliers()
              this.addDialogVisible = false
              this.showCancelMessage = false;
            } else {
              this.$message.error(res.data.msg)
            }
          }else{
            this.$message.error("手机号输入不正确，请重新输入")
          }

        } else {
          this.$message.error('请确保信息完整！至少填写供应商名称')
          return false;
        }
      })
    },


    async submit(){
      if (this.supplierData.length >= 3) {
        this.$confirm('确认提交审批吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = this.formData.projectId
          let res = await SubmitPotentialSuppliers(data);
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '提交成功!'
            });
            this.formData.potentialsupplierSubmitStatus = '已提交'
            await this.selectAddPotentialSuppliers();
            const currentDate = new Date();
            this.formData.potentialsupplierSubmitTime = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')} ${currentDate.getHours().toString().padStart(2, '0')}:${currentDate.getMinutes().toString().padStart(2, '0')}:${currentDate.getSeconds().toString().padStart(2, '0')}`;

          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消提交'
          });
        });
      } else {
        this.$message.error('至少需要三个潜在供应商');
      }
    },

    //当点击返回按钮，返回到potentialSuppliers页面
    goBack() {
      this.$router.push('potentialSuppliers');
    },
  },

};
</script>

<style>


.add-button {
  margin-left: 220px;
  margin-top: 40px;
}

.back-button {
  position: fixed;
  bottom: 20px;
  margin-left: 1%;
  font-size: 16px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 50px;
}
</style>

